﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using EFCore.AspNet.Sample.Data;
using EFCore.AspNet.Sample.Models;

namespace EFCore.AspNet.Sample.Pages.Students
{
    public class EditModel : PageModel
    {
        private readonly EFCore.AspNet.Sample.Data.SchoolContext _context;

        public EditModel(EFCore.AspNet.Sample.Data.SchoolContext context)
        {
            _context = context;
        }

        [BindProperty]
        public Student Student { get; set; }
        public async Task<IActionResult> OnGetAsync(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            Student = await _context.Students.FindAsync(id);

            if (Student == null)
            {
                return NotFound();
            }
            return Page();
        }

        /// <summary>
        /// 实体可能处于以下状态之一：
        /// Added：数据库中尚不存在实体。 SaveChanges 方法发出 INSERT 语句。
        /// Unchanged：无需保存对该实体所做的任何更改。 从数据库中读取实体时，该实体具有此状态。
        /// Modified：已修改实体的部分或全部属性值。 SaveChanges 方法发出 UPDATE 语句。
        /// Deleted：已标记该实体进行删除。 SaveChanges 方法发出 DELETE 语句。
        /// Detached：数据库上下文未跟踪该实体。
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        // To protect from overposting attacks, enable the specific properties you want to bind to, for
        // more details, see https://aka.ms/RazorPagesCRUD.
        public async Task<IActionResult> OnPostAsync(int id)
        {
            var studentToUpdate = await _context.Students.FindAsync(id);

            if (studentToUpdate == null)
            {
                return NotFound();
            }

            if (await TryUpdateModelAsync<Student>(
                studentToUpdate,
                "student",
                s => s.FirstMidName, s => s.LastName, s => s.EnrollmentDate))
            {
                await _context.SaveChangesAsync();
                return RedirectToPage("./Index");
            }

            return Page();
        }

        private bool StudentExists(int id)
        {
            return _context.Students.Any(e => e.ID == id);
        }
    }
}
